package cn.lf.config;

import cn.lf.entity.SysUser;
import cn.lf.filter.CustomerJwtToken;
import cn.lf.mapper.SysUserMapper;
import cn.lf.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 客户登录鉴权
 */
@Component
@Slf4j
public class CustomerShiroRealm extends AuthenticatingRealm {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomerJwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (token == null) {
            throw new AuthenticationException("token为空!");
        }
        // 校验token有效性
        if (!JwtUtils.verify(token)){
            throw new AuthenticationException("无效Token，请重新登录!");
        }
        String userName = JwtUtils.getUsername(token);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(SysUser::getUserName,userName);

        List<SysUser> userList = sysUserMapper.selectList(lambdaQueryWrapper);

        if (userList.isEmpty()){
            throw new AuthenticationException("异常Token，请重新登录!");
        }
        return new SimpleAuthenticationInfo(userList.get(0), token, getName());
    }

    @Override
    protected void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }
}
